<template>
  <k-view class="pk-container">
    <ConfirmDialog
      v-if="showNoDataDialog"
      title="提示"
      content="未查询到该公司的得分信息，请返回挑选其他公司进行对比"
      confirm-text="知道了"
      hide-cancel
      @success="goback"
      @fail="goback"
    ></ConfirmDialog>
    <k-view class="pk-content">
      <k-text class="content-title">PK得分明细</k-text>
      <k-view class="pk-img">
        <k-view class="pk-img-item pk-img-item1">
          <k-text class="name">{{ stockInfo.stock1.stockName }}</k-text>
          <k-text class="code">{{ stockInfo.stock1.stockCode }}</k-text>
          <k-text class="score-text"
            >综合评分<k-text class="score">{{ stockInfo.stock1.score }}</k-text
            >分<k-image
              :src="like"
              class="like like1"
              v-if="stockInfo.stock1.score > stockInfo.stock2.score"
          /></k-text>
        </k-view>
        <k-view class="pk-img-item pk-img-item2">
          <k-text class="name"
            ><k-image
              v-if="hasConversion"
              :src="conversion"
              class="conversion"
              @click.stop="goback(true)"
            />{{ stockInfo.stock2.stockName }}</k-text
          >
          <k-text class="code">{{ stockInfo.stock2.stockCode }}</k-text>
          <k-text class="score-text"
            ><k-image
              :src="like"
              class="like like2"
              v-if="stockInfo.stock1.score < stockInfo.stock2.score"
            />综合评分<k-text class="score">{{ stockInfo.stock2.score }}</k-text
            >分</k-text
          >
        </k-view>
      </k-view>
      <StockScoreTabs :modelValue="activeTab.index" @change="handleScoreTabChange" />
      <k-view class="specific-score">
        <k-text class="specific-score-desc specific-score-desc1"
          ><k-text class="name">{{ stockInfo.stock1.stockName }}</k-text
          >{{ activeTab.name }}得分为<k-text class="score">{{
            activeTab.stock1.score || '--'
          }}</k-text
          >分</k-text
        >
        <k-text class="specific-score-desc specific-score-desc2"
          ><k-text class="name">{{ stockInfo.stock2.stockName }}</k-text
          >{{ activeTab.name }}得分为<k-text class="score">{{
            activeTab.stock2.score || '--'
          }}</k-text
          >分</k-text
        >
      </k-view>
      <k-text class="desc"
        >健康指数得分均为基于公开数据并结合相关算法进行整理所得的计算结果，本产品力求但无法保证数据的准确性和完整性，健康得分不构成对任何人的投资建议，请谨慎参考</k-text
      >
    </k-view>
    <Table
      :stock1="stockInfo.stock1"
      :stock2="stockInfo.stock2"
      :tableData="{
        tableData1: activeTab.stock1.tableData,
        tableData2: activeTab.stock2.tableData,
      }"
      :auth="auth"
      @hasClickBuy="hasClickBuy"
      :activeName="activeTab.name"
    />
  </k-view>
</template>

<script setup lang="ts">
import Apis from '@king-fisher/apis';
import like from '@/assets/pk/like.png';
import conversion from '@/assets/pk/conversion.png';
import { onMounted, reactive, ref } from 'vue';
import StockScoreTabs from '@/components/StockDiagnosis/listTabs.vue';
import Table from '@/components/Pk/Table.vue';
import ConfirmDialog from '@/components/Intro/ConfirmDialog.vue';
import { scoreDetailList } from '../../scripts/scoreDetail';
import type { Stock, StockInfo, Query, ActiveTab } from '@/types/pk';
import { Auth } from '@/types/pk.d.ts';
import { getCompanyOverview, getStockScore } from '@/apis/index';
import { formatChgString, navigateBack, setCookie, caniuse, getUrlSearch } from '@/utils/index';
import fl from '@king-fisher/falcon';
import { sendPageStat, sendClickStat } from '@/utils/stat';
import { PAGEID } from '@/config/stat';
import getThemeHooks from '@/hooks/getThemeHooks';

const { getTheme, initTheme, onThemeChange } = getThemeHooks();

const auth = ref<{ stock1: Auth; stock2: Auth }>({ stock1: Auth.free, stock2: Auth.free });
// 是否有返回按钮
const hasConversion = ref<boolean>(false);
// pk两边的股票信息
const stockInfo: StockInfo = reactive({
  stock1: { stockCode: '--', stockName: '--', market: '--', score: '--' },
  stock2: { stockCode: '--', stockName: '--', market: '--', score: '--' },
});
// 是否展示dialog
const showNoDataDialog = ref<boolean>(false);
const goback = (isConversion: boolean = false) => {
  if (isConversion) {
    sendClickStat(`${PAGEID.PK}.change.click`);
  }
  navigateBack();
  showNoDataDialog.value = false;
};
// 当前选中的tab的内容
const activeTab: ActiveTab = reactive({
  index: scoreDetailList[0].id,
  name: scoreDetailList[0].name,
  key: scoreDetailList[0].key,
  stock1: {
    score: 0,
    tableData: [],
  },
  stock2: {
    score: 0,
    tableData: [],
  },
});
// 切换tab回调
const handleScoreTabChange = (current: number, name: string) => {
  if (activeTab.index === current) {
    return;
  }
  sendClickStat(`${PAGEID.PK}.system.${current}.click`);
  activeTab.index = current;
  activeTab.name = name;
  const resObj = scoreDetailList.find((item: any) => {
    return item.id == current;
  });
  if (resObj) {
    activeTab.key = resObj.key;
    getStockScoreInfo();
  }
};
const dealError = () => {
  Apis.Toast.show('数据异常，请稍后重试！');
};
// 获取综合得分
const getCompositeScore = () => {
  const dealRes = (res: any, param: Stock) => {
    if (res.status_code) {
      Apis.Toast.show('暂未查询到相关信息');
      return;
    }
    if (!res.data) {
      showNoDataDialog.value = true;
      return;
    }
    stockInfo[param].score = formatChgString(res.data.composite_score, 2);
  };
  getCompanyOverview(stockInfo.stock1.stockCode)
    .then(res => {
      dealRes(res, 'stock1');
    })
    .catch(dealError);
  getCompanyOverview(stockInfo.stock2.stockCode)
    .then(res => {
      dealRes(res, 'stock2');
    })
    .catch(dealError);
};
// 获取单系统得分
const getStockScoreInfo = () => {
  const dealRes = (res: any, param: Stock) => {
    if (res.status_code) {
      Apis.Toast.show('暂未查询到相关信息');
      return;
    }
    auth.value[param] = res.data.auth;
    activeTab[param].score = formatChgString(res.data.score, 2);
    activeTab[param].tableData = res.data.index2_list;
  };
  // 被对比股票的返回值
  let res1: any = null;
  // 对比股票的返回值
  let res2: any = null;
  Promise.all([
    getStockScore(stockInfo.stock1.stockCode, activeTab.key).then(res => {
      res1 = res;
    }),
    getStockScore(stockInfo.stock2.stockCode, activeTab.key).then(res => {
      res2 = res;
    }),
  ])
    .then(() => {
      activeTab.stock1.tableData = [];
      activeTab.stock2.tableData = [];
      dealRes(res1, 'stock1');
      dealRes(res2, 'stock2');
    })
    .catch(dealError);
};
// 记录首次点击购买
const hasClickBuy = () => {
  fl.onAppear(() => {
    getStockScoreInfo();
  });
};
onMounted(() => {
  setCookie().then((id: any) => {
    sessionStorage.setItem('userIdKey', id);
    sendPageStat(`${PAGEID.PK}`);
  });
  getTheme();
  initTheme();
  onThemeChange();
  const query: Query = getUrlSearch();
  stockInfo.stock1.stockCode = query.stockCode1 || '--';
  stockInfo.stock1.stockName = decodeURIComponent(query.stockName1 || '--');
  stockInfo.stock2.stockCode = query.stockCode2 || '--';
  stockInfo.stock2.stockName = decodeURIComponent(query.stockName2 || '--');
  hasConversion.value = query.hasConversion === 'true';
  if (stockInfo.stock1.stockCode && stockInfo.stock2.stockCode) {
    getCompositeScore();
    getStockScoreInfo();
  }
});
</script>

<style scoped lang="less">
.pk-container {
  position: relative;
  padding: 12px;
  background-color: #f5f5f5;

  .pk-content {
    background-color: #ffffff;
    padding: 20px 20px 0;
    border-radius: 16px 16px 0 0;
    box-sizing: border-box;

    :deep(.stock-score-tabs) {
      padding-top: 4px;
      height: 130px;
    }

    .content-title {
      font-size: 36px;
      color: #262626;
      font-weight: 500;
    }

    .pk-img {
      width: 698px;
      height: 192px;
      display: flex;
      margin-top: 26px;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      background-image: url('//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/9d66d3dd-4248-44fe-8156-76ea411125b2.png');

      &-item {
        width: 50%;
        height: 192px;
        display: flex;
        flex-direction: column;

        .like {
          width: 24px;
          height: 24px;
        }

        .like1 {
          margin-left: 12px;
        }

        .like2 {
          margin-right: 12px;
        }

        .conversion {
          margin-right: 12px;
          width: 40px;
          height: 40px;
        }

        .name {
          display: flex;
          align-items: center;
          font-family: PingFangSC-Medium;
          font-size: 32px;
          color: #ffffff;
          text-align: center;
          font-weight: bold;
          margin-top: 24px;
        }

        .code {
          opacity: 0.9;
          font-family: PingFangSC-Regular;
          font-size: 26px;
          color: #ffffff;
          text-align: center;
          font-weight: 400;
          margin-top: 4px;
        }

        .score-text {
          display: flex;
          align-items: center;
          font-family: PingFangSC-Regular;
          font-size: 28px;
          color: #ffffff;
          text-align: center;
          line-height: 40px;
          font-weight: 400;
          margin-top: 16px;

          .score {
            font-family: THSJinRongTi-Medium;
            color: #ffffff;
            font-weight: bold;
          }
        }
      }

      &-item1 {
        align-items: flex-start;
        padding-left: 24px;
      }

      &-item2 {
        align-items: flex-end;
        padding-right: 24px;
      }
    }

    .specific-score {
      background-color: #f7f7f9;
      border-radius: 4px;
      width: 686px;
      height: 120px;
      padding-left: 24px;
      padding-top: 16px;

      &-desc {
        display: flex;
        align-items: center;
        font-family: PingFangSC-Regular;
        font-size: 26px;
        color: rgba(0, 0, 0, 0.84);
        line-height: 36px;
        font-weight: 400;

        .name {
          position: relative;
          font-family: PingFangSC-Medium;
          font-weight: bold;
        }

        .score {
          margin-left: 10px;
          font-family: PingFangSC-Medium;
          color: #ff2436;
          font-weight: bold;
        }
      }

      &-desc1 {
        .name {
          color: #ff2436;

          &::after {
            content: '';
            position: absolute;
            width: 100%;
            height: 8px;
            left: 0;
            bottom: 2px;
            background-color: rgba(255, 36, 54, 0.2);
            border-radius: 4px;
          }
        }

        .score {
          color: #ff2436;
        }
      }

      &-desc2 {
        margin-top: 16px;

        .name {
          color: #3366ff;

          &::after {
            content: '';
            position: absolute;
            width: 100%;
            height: 8px;
            left: 0;
            bottom: 2px;
            background-color: rgba(51, 102, 255, 0.2);
            border-radius: 4px;
          }
        }

        .score {
          color: #07ab4b;
        }
      }
    }

    .desc {
      margin-top: 24px;
      padding-bottom: 24px;
      font-family: PingFangSC-Regular;
      font-size: 26px;
      color: rgba(0, 0, 0, 0.4);
      font-weight: 400;
      border-bottom: 1px solid #edeff2;
    }
  }
}

[theme-mode='black'] .pk-container {
  background-color: #020202;

  .pk-content {
    background-color: #121212;

    .pk-img {
      background-image: url(//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/b1ab5f37-1aa5-4c95-9d09-0238924a444a.png);
    }

    .content-title {
      color: #ffffff;
    }

    .desc {
      color: rgba(255, 255, 255, 0.4);
      border-bottom: 1px solid rgba(255, 255, 255, 0.06);
    }

    .specific-score {
      background-color: #212121;

      &-desc {
        color: rgba(255, 255, 255, 0.84);
      }
    }
  }
}
</style>
